<template>
  <div class="auth-page">
    <div class="auth-container">
      <div class="auth-right">
        <div class="auth-logo">
          <img src="@/assets/logo.svg" alt="Logo">
          <h1>用户认证系统</h1>
        </div>
        <div class="auth-subtitle">欢迎登录</div>
        <form class="auth-form" @submit.prevent="handleLogin">
          <div class="form-group">
            <label for="username" class="form-label">用户名</label>
            <div class="relative">
              <input
                  v-model="form.username"
                  type="text"
                  id="username"
                  placeholder="输入用户名"
                  :class="{ 'border-red-500': errors.username }"
                  @blur="validateField('username')"
                  required
              />
              <div v-if="errors.username" class="absolute -bottom-6 left-0 text-red-500 text-xs">
                {{ errors.username }}
              </div>
            </div>
          </div>

          <div class="form-group">
            <label for="password" class="form-label">密码</label>
            <div class="relative password-input">
              <input
                  v-model="form.password"
                  :type="showPassword ? 'text' : 'password'"
                  id="password"
                  placeholder="输入密码"
                  :class="{ 'border-red-500': errors.password }"
                  @blur="validateField('password')"
                  required
              />
              <button
                  type="button"
                  @click="showPassword = !showPassword"
                  class="toggle-password"
              >
                <font-awesome-icon :icon="showPassword ? 'eye-slash' : 'eye'" />
              </button>
              <div v-if="errors.password" class="absolute -bottom-6 left-0 text-red-500 text-xs">
                {{ errors.password }}
              </div>
            </div>
          </div>

          <div class="form-options">
            <a href="#" class="forgot-password">忘记密码?</a>
          </div>

          <button
              type="submit"
              class="auth-button"
              :disabled="isLoading || !formValid"
          >
            <span v-if="isLoading">
              <font-awesome-icon icon="spinner" spin /> 登录中...
            </span>
            <span v-else>登录</span>
          </button>

          <div class="auth-footer">
            没有账户? <router-link to="/register">注册</router-link>
          </div>
        </form>

        <!-- 错误提示区域 -->
        <div v-if="errorMessage" class="error-message">
          <font-awesome-icon icon="exclamation-circle" />
          <span>{{ errorMessage }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';

const authStore = useAuthStore();
const router = useRouter();

// 表单数据
const form = ref({
  username: '',
  password: ''
});

// 表单错误
const errors = ref({
  username: '',
  password: ''
});

// 状态管理
const errorMessage = ref('');
const showPassword = ref(false);
const isLoading = ref(false);

// 表单验证规则
const validationRules = {
  username: [
    { check: v => !!v.trim(), message: '用户名不能为空' }
  ],
  password: [
    { check: v => !!v.trim(), message: '密码不能为空' },
    { check: v => v.length >= 6, message: '密码长度至少6位' }
  ]
};

// 验证字段
const validateField = (field) => {
  const value = form.value[field];
  const rule = validationRules[field][0];

  if (!rule.check(value)) {
    errors.value[field] = rule.message;
    return false;
  }

  errors.value[field] = '';
  return true;
};

// 验证整个表单
const validateForm = () => {
  return validateField('username') && validateField('password');
};

// 表单有效性计算属性
const formValid = computed(() => {
  return !errors.value.username && !errors.value.password &&
      form.value.username.trim() && form.value.password.trim();
});

// 登录处理
const handleLogin = async () => {
  errors.value = { username: '', password: '' };
  errorMessage.value = '';

  if (!validateForm()) {
    return;
  }

  isLoading.value = true;
  errorMessage.value = '';

  try {
    await authStore.login({
      username: form.value.username.trim(),
      password: form.value.password.trim()
    });

    // 检查登录是否成功
    if (authStore.isAuthenticated) {
      await router.push('/dashboard');
    } else {
      errorMessage.value = '用户名或密码错误';
    }
  } catch (error) {
    // 根据后端返回的错误类型显示不同提示
    if (error.response) {
      switch (error.response.status) {
        case 400:
          errorMessage.value = '参数校验失败: ' + (error.response.data.message || '请检查输入');
          break;
        case 401:
          errorMessage.value = '用户名或密码错误';
          break;
        case 403:
          errorMessage.value = '账户已被禁用';
          break;
        default:
          errorMessage.value = '登录失败: ' + (error.response.data.message || '请稍后再试');
      }
    } else {
      errorMessage.value = '网络错误，请检查连接后重试';
    }
    form.value.password = '';
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时检查登录状态
if (authStore.isAuthenticated) {
  router.push('/dashboard');
}
</script>

<style scoped>
/* 样式保持不变 */
.auth-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 2rem;
}

.auth-container {
  display: flex;
  max-width: 500px;
  width: 100%;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.auth-right {
  flex: 1;
  padding: 3rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.auth-logo {
  margin-bottom: 2rem;
  text-align: center;
}

.auth-logo img {
  height: 60px;
  margin-bottom: 1rem;
}

.auth-logo h1 {
  font-size: 2rem;
  font-weight: 600;
  margin: 0;
}

.auth-subtitle {
  font-size: 1.1rem;
  opacity: 0.9;
  margin-bottom: 2rem;
  text-align: center;
}

.auth-form {
  width: 100%;
}

.form-group {
  margin-bottom: 2rem;
}

.form-label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #4a5568;
}

.form-group input {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.2s;
}

.form-group input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.password-input {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #a0aec0;
  cursor: pointer;
  padding: 0.5rem;
}

.toggle-password:hover {
  color: #667eea;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.forgot-password {
  color: #667eea;
  text-decoration: none;
  font-size: 0.9rem;
  transition: color 0.2s;
}

.forgot-password:hover {
  color: #434190;
}

.auth-button {
  width: 100%;
  padding: 1rem;
  font-size: 1.1rem;
  border: none;
  border-radius: 8px;
  background-color: #667eea;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}

.auth-button:disabled {
  background-color: #b3b3b3;
  cursor: not-allowed;
}

.auth-footer {
  text-align: center;
  margin-top: 1rem;
  font-size: 0.9rem;
}

.auth-footer a {
  color: #667eea;
  text-decoration: none;
}

.auth-footer a:hover {
  text-decoration: underline;
}

.error-message {
  padding: 1rem;
  background-color: #f8d7da;
  color: #721c24;
  border-radius: 8px;
  display: flex;
  align-items: center;
  margin-top: 1rem;
  gap: 0.5rem;
}

.border-red-500 {
  border-color: #ef4444 !important;
}

.text-red-500 {
  color: #ef4444;
}
</style>